import { ClockCircleOutlined, ShareAltOutlined, StarFilled, StarOutlined } from '@ant-design/icons';
import { message } from 'antd';
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import './ContentCard.scss';

interface ContentCardProps {
  app: {
    title: string;
    description: string;
    date: string;
    views: string;
    likes: string;
    comments: number;
    downloads: string;
    shares: string;
    username: string;
    favorites: string;
    tags: string[];
    image: string;
    link: string;
    datasetId: string;
  };
}

const ContentCard: React.FC<ContentCardProps> = ({ app }) => {
  const navigate = useNavigate();
  const [collected, setCollected] = useState(false);
  const [liked, setLiked] = useState(false);
  const [downloads, setDownloads] = useState(0);
  const [likes, setLikes] = useState(0);
  const [favorites, setFavorites] = useState(0);
  const [views, setViews] = useState(0);

  const handleClick = () => {
    axios.post('http://127.0.0.1:8082/clickDataset', { targetId: app.datasetId })
      .then(response => {
        console.log(response.data);
        setViews(prev => prev + 1);
        navigate(`/shuju/xiangqing`, { state: { app } });
      })
      .catch(error => {
        console.error('Error clicking dataset:', error);
        navigate(`/shuju/xiangqing`, { state: { app } });
      });

    console.log(app.datasetId);
    console.log(app);
  };

  const handleAction = (action: 'download' | 'like') => {
    if (action === 'download') {
      const downloadUrl = 'http://127.0.0.1:8082/downloadDataset';
      console.log('id为', app.datasetId);
      axios.post(downloadUrl, { targetId: app.datasetId })
        .then(response => {
          console.log(response.data);
          setDownloads(prev => prev + 1);
          const downloadLink = response.data.msg;
          if (downloadLink) {
            window.open(downloadLink, '_blank');
          }
        })
        .catch(error => {
          console.error('Error fetching download link:', error);
        });
    } else if (action === 'like') {
      const url = 'http://127.0.0.1:8082/shareDataset';
      axios.post(url, { targetId: app.datasetId })
        .then(response => {
          console.log(response.data);
          setLikes(prev => prev + 1);
          const shareLink = response.data.msg;
          if (shareLink) {
            navigator.clipboard.writeText(shareLink).then(() => {
              message.success('链接已复制到剪贴板');
              console.log('Link copied to clipboard:', shareLink);
            }).catch(error => {
              console.error('Error copying link to clipboard:', error);
            });
          }
        })
        .catch(error => {
          console.error('Error clicking dataset:', error);
        });
    }
  };

  const handleFavorite = () => {
    const url = 'http://127.0.0.1:8082/favoriteDataset';
    axios.post(url, { targetId: app.datasetId })
      .then(response => {
        console.log(response.data);
        setFavorites(prev => prev + 1);
        setCollected(true);
      })
      .catch(error => {
        console.error('Error favoriting dataset:', error);
      });
  };

  useEffect(() => {
    console.log("Rendering ContentCard with data:", app);
    setDownloads(Number(app.downloads));
    setLikes(Number(app.likes));
    setFavorites(Number(app.favorites));
    setViews(Number(app.views));
    setCollected(false);
    setLiked(false);
  }, [app]);

  return (
    <div className="data-item">
      <div className="card-top">
        <img src={app.image} alt={app.title} className="data-image" />
        <div className="data-details">
          <div className="card-top-left">
            <h2>{app.title}</h2>
            <div className="favorites">
              <span
                onClick={() => {
                  if (!collected) handleFavorite();
                }}
                style={{ display: 'inline-flex', alignItems: 'center', padding: '0.0625rem 0.3125rem', color: '#81838f', fontSize: '1.125rem' }}
              >
                {collected ? <StarFilled style={{ color: 'gold', fontSize: '1.125rem', marginRight: '0.125rem' }} /> : <StarOutlined style={{ fontSize: '1.125rem', marginRight: '0.125rem' }} />}
                {favorites}
              </span>
            </div>
          </div>
          <div className="tags">
            {app.tags.slice(0, 3).map((tag, tagIndex) => (
              <span key={tagIndex} className="tag">
                {tag}
              </span>
            ))}
          </div>
          <p className="description">{app.description}</p>
        </div>
      </div>
      <div className="card-bottom">
        <div className="meta">
          <span style={{ fontSize: '1.125rem' }}><img src="/OIP.jpg" alt="用户名" /> {app.username}</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', color: '#81838f', fontSize: '1.125rem' }}>
            <ClockCircleOutlined style={{ fontSize: '1.125rem', marginRight: '0.125rem' }} /> {app.date}
          </span>
          <span style={{ fontSize: '1.125rem' }} onClick={() => handleAction('download')}><img src="/31.png" alt="下载量" style={{ marginBottom: '0.1875rem' }} /> {downloads}</span>
          <span onClick={() => { setLiked(!liked); handleAction('like'); }} style={{ display: 'inline-flex', alignItems: 'center', color: '#81838f', fontSize: '1.125rem' }}>
            <ShareAltOutlined style={{ fontSize: '1.125rem', marginRight: '0.0625rem' }} /> {likes}
          </span>
        </div>
        <button className="detail-button" onClick={handleClick}>查看详情</button>
      </div>
    </div>
  );
};

export default ContentCard;
